<?php

class Users_Controller_Index extends Light_Controller
{
	public function loginAction()
	{
	    if ($this->view->identity()) {
	        $this->view->redirect(array(), 'default');
	    }

	    $data   = array();
	    $errors = array();

        if ($this->getRequest()->isPost()) {
            $model  = new Users_Model_Index();
            $data   = $this->getRequest()->getPost();
            $errors = $model->validate($data);
            if (empty($errors)) {
                if ($model->login($data['name'], $data['password'])) {
                    $this->view->redirect(array(), 'default');
                }
                $errors['login'] = 'Invalid credentials';
            }
        }

        $this->view->assign('data', $data);
        $this->view->assign('errors', $errors);
	}

	public function logoutAction()
	{
	    session_destroy();

	    $this->view->redirect(array(), 'default');
	}

	public function infoAction()
	{
        $id = (int) $this->_getParam('id');

        $model = new Users_Model_Index();

        $item = $model->find($id)->current();

        if ($item === null) {
            throw new Light_Exception('Invalid request');
        }

        $this->view->assign('item', $item);
	}

	public function profileAction()
	{
	    $user = $this->view->identity();

	    $model = new Users_Model_Index();

        $item = $model->find($user->id)->current();

        if ($item === null) {
            throw new Light_Exception('Invalid request');
        }

        $data   = $item->toArray();
        $errors = array();

        if ($this->getRequest()->isPost()) {

            $data   = $this->getRequest()->getPost();

            $errors = $model->validate($data, $item);

            if (empty($errors)) {
                $item->setFromArray($data);
                $item->save();
                $model->updateSession($item);
                $this->view->flashMessage()->setMessage();
                $this->view->redirect();
                $errors['password'] = 'Error';
            }
        }

        $this->view->assign('item', $item);
        $this->view->assign('data', $data);
        $this->view->assign('errors', $errors);
	}
}